package module

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"
)

var Myapplog *log.Logger

func GetMycat() (result CnafMyCatMetric) {
	dsn := "root:123456@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("错误")
	} else {
		fmt.Println("连接成功")
	}
	db.Raw("select NAME_,VALUE ,REV_ from srv_property where NAME_=?", "next.dbid").Scan(&result)
	return result
}

func GetMysql(teant string) (result CnafMysqlMetric) {
	dsn := fmt.Sprintf("root:airport@tcp(10.0.1.10:3306)/%s?charset=utf8mb4&parseTime=True", teant)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: initLogger(),
	})
	if err != nil {
		panic("数据库连接错误")
	} else {
		Myapplog.Printf("%s连接成功", teant)
	}
	var count1, count2, count3 int64

	db.Table("flightinfo").Distinct("flop").Count(&count1)
	db.Table("flight_change").Distinct("flop").Count(&count2)
	db.Table("srv_task").Distinct("flop").Count(&count3)
	result = CnafMysqlMetric{
		FlightInfo:  float64(count1),
		FlightChage: float64(count2),
		SrvTask:     float64(count3),
	}
	return result
}

func GetAmq() {

	type JolokiaRequest struct {
		Type      string `json:"type"`
		MBean     string `json:"mbean"`
		Attribute string `json:"attribute,omitempty"`
	}

	type JolokiaResponse struct {
		Request JolokiaRequest `json:"request"`
		Value   interface{}    `json:"value"`
		Error   string         `json:"error,omitempty"`
		Status  int            `json:"status"`
	}

	url := "http://192.168.84.200:8161/api/jolokia/read"
	username := "admin" // 替换为你的用户名
	password := "admin" // 替换为你的密码

	// 查询所有订阅者
	requestPayload := JolokiaRequest{
		Type:  "read",
		MBean: "org.apache.activemq:Type=Subscription,SubscriptionName=*",
	}

	payloadBytes, _ := json.Marshal(requestPayload)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
	if err != nil {
		panic(err)
	}
	req.SetBasicAuth(username, password)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	var jolokiaResponse JolokiaResponse
	json.Unmarshal(body, &jolokiaResponse)

	if jolokiaResponse.Error != "" {
		fmt.Printf("Error: %s\n", jolokiaResponse.Error)
		return
	}

	subscribers := jolokiaResponse.Value.([]interface{})
	activeDurableCount := 0

	for _, sub := range subscribers {
		subMap := sub.(map[string]interface{})
		if subMap["durable"].(bool) && subMap["active"].(bool) {
			activeDurableCount++
		}
	}

	fmt.Printf("Active Durable Topic Subscribers: %d\n", activeDurableCount)

}

func initLogger() logger.Interface {
	logFile, err := os.OpenFile("gorm.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		panic("无法打开或创建日志文件")
	}

	Myapplog = log.New(logFile, "[myapp] ", log.Ldate|log.Ltime|log.Lshortfile)
	//初始化日志
	return logger.New(
		log.New(logFile, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      false,
		},
	)
}
